<template>
  <div class="report-material">
    <!-- 文件上传 -->
    <div class="upload-wrapper">
      <el-form ref="postForm">
        <el-form-item label="审批类型：">
          <el-radio-group v-model="approvalType" size="small">
            <el-radio-button label="upload">上报审批</el-radio-button>
            <el-radio-button label="holiday">请假申请</el-radio-button>
            <el-radio-button label="useCar">公务用车申请</el-radio-button>
            <el-radio-button label="officeBuy">办公用品采购申请</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <upload-approval-form
            ref="uploadForm"
            v-if="approvalType === 'upload'"
            @onChangeProcess="handleChangeUploadProcess"
          />
          <user-car-pager 
            ref="useCarForm" 
            v-if="approvalType === 'useCar'" 
          />
          <office-buy-pager
            ref="officeBuy" 
            v-if="approvalType === 'officeBuy'" 
          />
          <witten
            ref="holiday" 
            v-if="approvalType === 'holiday'" 
            showLeaveStatics
          />
        </el-form-item>

        <el-form-item :label="uploadProcessType === '材料审批' ? '审批人' : approvalLeaderMap[approvalType]">
          <el-tag v-for="user in selectedUsers" :key="user.first_name">
            {{ user.first_name }}
          </el-tag>
          <el-button
            round
            type="text"
            size="small"
            icon="el-icon-user"
            style="padding-left: 0"
            @click="dialogUserVisible = true"
            >选择人员</el-button
          >
          <el-button
            size="small"
            icon="el-icon-plus"
            style="margin-top: 9px"
            type="primary"
            @click="handleSubmit"
            :disabled="uploadLoading"
            >提交</el-button
          >
          </el-form-item>
      </el-form>
    </div>
    <!-- 上报历史 -->
    <div class="history">
      <div>历史记录</div>
      <upload-history
        v-if="approvalType === 'upload'"
        :dataSource="tableList"
        :loading="listLoading"
        @onDeleteUpload="handDelFile"
        @onShowMonitor="handleShowMonitor"
      />
      <use-car-history
        v-else-if="approvalType === 'useCar'"
        :dataSource="tableList"
        :loading="listLoading"
        @onDeleteUseCar="handDelUseCar"
        @onShowMonitor="handleShowMonitor"
      />
      <office-buy-history
        v-else-if="approvalType === 'officeBuy'"
        :dataSource="tableList"
        :loading="listLoading"
        @onDeleteUseCar="handDelOfficeBuy"
        @onShowMonitor="handleShowMonitor"
      />
      <holiday-history
        v-else-if="approvalType === 'holiday'"
        :dataSource="tableList"
        :loading="listLoading"
        @onDeleteHoliday="handDelHoliday"
        @onShowMonitor="handleShowMonitor"
      />
      <el-empty v-else :image-size="100" description="暂无数据" />
      <div class="pageWrapper">
        <pagination
          v-show="total > pageSize"
          :total="total"
          :layout="'total, prev, pager, next'"
          :page.sync="resForm.page"
          :limit.sync="pageSize"
          @pagination="handlePage"
        />
      </div>
    </div>
    <!-- 流程监控 -->
    <process-monitor
      ref="process"
      :fromTask="true"
      :pager="selectedRecord"
      :activities="activities"
      :processCode="processCode"
      :processStatics="processStatics"
      @onCloseDialog="handleCloseDialog"
    />
    <!-- 打开人员安排窗口  -->
    <div class="selectedUser">
      <el-dialog width="80%"  title="人员安排" :visible.sync="dialogUserVisible">
        <user-manager :isRadio="true" :onSelectUsers="getSelectUsers" />
      </el-dialog>
    </div>
  </div>
</template>
<script>
import axios from "axios";
import Cookies from "js-cookie";
import moment from 'moment'
import { mapGetters } from "vuex";
import { parseTime, previewFileAppendPath } from "@/utils/index.js";
import { updateFileInfo } from "@/api/document";
import {
  getUploadApprovalFileHistory,
  deleteUploadApprovalFileHistory,
  createUploadApprovalTask,
  createHolidayApprovalTask,
  getHolidayApprovalTaskHistory,
  deleteHolidayApprovalTaskHistory,
  createUseCarApprovalTask,
  getUseCarApprovalTaskHistory,
  deleteUseCarApprovalTaskHistory,
  createOfficeBuyApprovalTask,
  getOfficeBuyApprovalTaskHistory,
  deleteOfficeBuyApprovalTaskInfo
} from "@/api/work";
import { postSendShortInfo } from '@/api/user'
import { getTaskProcessInfo1, startProcess, delProcessDataByTaskId } from "@/api/workflow.js";
export default {
  name: "ReportMaterials",
  data() {
    return {
      fileList: [],
      selectedUsers: [],
      dialogUserVisible: false, // 人员安排
      pageSize: 10,
      total: 0,
      uploadLoading: false,
      listLoading: true,
      tableList: [],
      resForm: {
        page: 1,
      },
      fileRecordForm: {
        issued_number: null,
        issued_date: null,
      },
      reportDesc: "",
      approvalType: "upload",
      approvalLeaderMap: {
        'upload': '值班领导',
        'useCar': '中心负责人',
        'holiday': '人教科审核',
        'officeBuy': '科室负责人',
      },
      uploadProcessType: '材料审批',
      processStatics: {
        curCount: 0,
        doneCount: 0,
        willCount: 0
      }, // 流程监控节点统计
      activities: [], // 流程监控数据
      selectedRecord: null, // 选中记录
      processCode: null // 审批流程代码
    };
  },
  computed: {
    ...mapGetters(["name", "id", "first_name", "department_name"]),
  },
  components: {
    UserManager: () =>
      import("@/views/markSys/taskCenter/components/userManager.vue"),
    processMonitor: () =>
      import("@/views/markSys/taskCenter/approve/handler/components/ProcessMinitor/index.vue"),
    Pagination: () => import("@/components/Pagination"),
    ImageType: () => import("@/components/ImageType"),
    UploadApprovalForm: () => import("./UploadApproval/Form"),
    UserCarPager: () =>
      import("@/views/markSys/taskCenter/components/UserCarPager"),
    Witten: () => import('@/views/markSys/components/Witten/index'),
    OfficeBuyPager: () => import('@/views/markSys/components/OfficeBuy/index'),
    UploadHistory: () => import("./HistoryRecord/Upload.vue"),
    UseCarHistory: () => import("./HistoryRecord/UseCar.vue"),
    OfficeBuyHistory: () => import("./HistoryRecord/OfficeBuy.vue"),
    HolidayHistory: () => import("./HistoryRecord/Holiday.vue"),
  },
  watch: {
    approvalType(value) {
      // 切换类型时，初始化请求参数
      this.initFetchRecord()
    },
  },
  mounted() {
    this.fetchUploadHistory();
  },
  methods: {
    parseTime,
    previewFileAppendPath,
    // 生成当前时间随机值
    generateUploadID() {
      const randomKey = Math.random().toString(16).substr(2, 10);
      const currentDate = parseTime(new Date(), "{y}{m}{d}{h}{i}");
      return `${currentDate}-${randomKey}`;
    },
    // 初始化请求
    initFetchRecord() {
      this.total = 0
      this.resForm.page = 1
      this.fetchUploadHistory();
    },
    // 修改上报流程
    handleChangeUploadProcess(value) {
      this.uploadProcessType = value
    },
    // 删除上传任务
    async handDelFile(index, row) {
      const { data } = await delProcessDataByTaskId(row.id);
      if (data.code == "200") {
        await deleteUploadApprovalFileHistory(row.id);
        this.$message.success("删除上报记录成功");
        this.initFetchRecord()
      }
    },
    // 删除公务用车任务
    async handDelUseCar(index, row) {
      const { data } = await delProcessDataByTaskId(row.id);
      if (data.code == "200") {
        await deleteUseCarApprovalTaskHistory(row.id);
        this.$message.success("删除公务用车申请记录成功");
        this.initFetchRecord()
      }
    },
    // 删除办公用品采购任务
    async handDelOfficeBuy(index, row) {
      const { data } = await delProcessDataByTaskId(row.id);
      if (data.code == "200") {
        await deleteOfficeBuyApprovalTaskInfo(row.id);
        this.$message.success("删除办公用品采购申请记录成功");
        this.initFetchRecord()
      }
    },
    // 删除请假任务
    async handDelHoliday(index, row) {
      const { data } = await delProcessDataByTaskId(row.id);
      if (data.code == "200") {
        await deleteHolidayApprovalTaskHistory(row.id);
        this.$message.success("删除请休假记录成功");
        this.initFetchRecord()
      }
    },
    // 显示流程监控dialog
    handleShowMonitor(row) {
      const { id } = row
      this.selectedRecord = {...row, approval_type: this.approvalType}
      getTaskProcessInfo1(id).then(res => {
        const { curCount, doneCount, willCount, proDefKey, data = [] } =
          (res.data && res.data.data) || {};
        this.activities = data;
        this.processCode = data[0] && data[0].procDefId.split(/\d+/)[0]
        this.processStatics = {
          taskId: id,
          modelName: proDefKey,
          curCount: curCount,
          doneCount: doneCount,
          willCount: willCount
        };
      });
      this.$refs.process.dialogProcessVisible = true;
      this.$refs.process.togglePage = false;
    },
    // 关闭流程监控触发事件
    handleCloseDialog() {
      this.activities = []
      this.processStatics = {
        ...this.processStatics,
        curCount: 0,
        doneCount: 0,
        willCount: 0
      }
    },
    // 上传文件
    async handleSubmit() {
      if (!this.selectedUsers.length) {
        const leaderDesc = this.uploadProcessType === '材料审批' ? '审批人' : this.approvalLeaderMap[this.approvalType]
        this.$message({
          message: `请选择${leaderDesc}！`,
          type: "warning",
        });
        return;
      }
      if (this.approvalType === "upload") {
        // 上报审批
        const { reportDesc, uploadProcessType, fileList } = this.$refs.uploadForm;
        if (!reportDesc || !fileList.length) {
          this.$message({
            message: "请输入上报描述及选择上传的文件！",
            type: "warning",
          });
          return;
        }
        await this.submitUploadApproval(reportDesc, uploadProcessType, fileList);
      } else if (this.approvalType === "useCar") {
        // 公务用车审批
        const { formData } = this.$refs.useCarForm;
        if(Object.values(formData).some(value => !value)) {
          this.$message({
            message: "请填写申请单所有内容！",
            type: "warning",
          });
          return;
        }
        formData.departmentName = this.department_name
        formData.applyer = this.first_name
        await this.submitUseCarApproval(formData);
      } else if (this.approvalType === "officeBuy") {
        // 办公用品审批
        const { dataSource } = this.$refs.officeBuy;
        if(dataSource.some(record => !record.bgyp)) {
          this.$message({
            message: "请将申请单填写内容补充完整！",
            type: "warning",
          });
          return;
        }
        await this.submitOfficeBuyApproval(dataSource);
      } else if (this.approvalType === "holiday") {
        // 请休假审批
        const { dateRange, holidayType, totalDay,address } = this.$refs.holiday;
        const {province,city,county} = address
        if (!dateRange.length) {
          this.$message({
            message: "请选择请休假时间！",
            type: "warning",
          });
          return;
        }
        if(!(province && city && county)){
          this.$message({
            message: "请填写请休假期间常住地！",
            type: "warning",
          });
          return;
        }
        const [startDate, endDate] = dateRange;
        const param = {
          owner: this.id,
          type: holidayType,
          start_date: moment(startDate).format("YYYY-MM-DD"),
          end_date: moment(endDate).format("YYYY-MM-DD"),
          leave_num: totalDay,
          leave_address:JSON.stringify([province,city,county])

        };
        await this.submitHolidyApproval(param);
      }
    },
    // 创建任务
    async createTask(desc) {
      return new Promise(async (resolve, reject) => {
        const { data } = await createUploadApprovalTask({
          time_stamp: this.generateUploadID(),
          desc,
        });
        if (data.id) {
          resolve(data.id);
        } else {
          reject();
        }
      });
    },
    // 上报文件
    async submitUploadApproval(reportDesc, uploadProcessType, fileList) {
      this.uploadLoading = true;
      const bussKey = await this.createTask(reportDesc);
      if (!bussKey) return;
      const uplaodMessage = this.$message({
        message: "正在上传文件，请稍等...",
        type: "success",
        duration: 0,
      });
      const form = new FormData();
      form.append("is_review", true);
      form.append("work_report", bussKey);
      fileList.forEach((e) => {
        form.append("url", e.raw);
      });
      axios.post("/api/Work/Files/", form).then(async (res) => {
        if (res) {
          uplaodMessage.close();
          this.$notify({
            title: "成功",
            message: "文件上传成功",
            type: "success",
            duration: 2000,
          });
          await this.executeApprove({
            bussKey,
            bussName: reportDesc,
            approvalType: "upload",
            processName: uploadProcessType === '值班审批' ? "TSPYFZBSB001" : "TSPCLSP001",
          });
          this.uploadLoading = false;
          this.fetchUploadHistory();
        }
      });
    },
    // 公务用车审批
    async submitUseCarApproval(param) {
      const { jsy_name, jsy_phone } = param
      const { data } = await createUseCarApprovalTask({jsy_name, jsy_phone, owner: this.id});

      const bussKey = data.id;
      await this.executeApprove({
        bussKey,
        bussName: `公务用车审批(${this.first_name})`,
        approvalType: "useCar",
        processName: "TSPGWYCSP01",
        // procInstVar: {
        fromData: {
          sp_status: "审批中",
          ...param
        },
      });
    },
    // 办公用品采购审批
    async submitOfficeBuyApproval(param) {
      const { data } = await createOfficeBuyApprovalTask(param);

      const bussKey = data.data;
      await this.executeApprove({
        bussKey,
        bussName: `办公用品采购审批(${this.first_name})`,
        approvalType: "officeBuy",
        processName: "TSPBGYPCG01"
      });
    },
    // 请假审批
    async submitHolidyApproval(param) {
      const { data } = await createHolidayApprovalTask(param);

      const bussKey = data.id;
      await this.executeApprove({
        bussKey,
        bussName: `请假审批(${this.first_name})`,
        approvalType: "leave",
        processName: "TSPZWBQJ001",
        procInstVar: {
          sp_status: "审批中",
        },
      });
    },
    // 执行流程
    async executeApprove({
      bussKey,
      bussName,
      approvalType,
      processName,
      fromData,
    }) {
      const leaders = this.selectedUsers.map((item) => item.id);
      const param = {
        businessKey: bussKey,
        bussName,
        bussType: "SP",
        targetUnitId: "",
        startUserId: this.id,
        startUserName: this.name,
        userList: leaders,
        approvalType,
        fromData,
      };
      const { data } = await startProcess(processName, param);
      if (data.message === "启动成功") {
        this.$notify({
          title: "提示",
          message: "启动流转成功",
          type: "success",
          duration: 2000,
        });
        // 上报审批发送短信
        if(approvalType === 'upload') {
          this.handleSendApprovalorInfo()
        }
        this.$router.push({ name: "HomePage" });
      } else {
        this.$notify({
          title: "提示",
          message: "启动流转失败",
          type: "error",
          duration: 2000,
        });
      }
    },
    async handleSendApprovalorInfo() {
      // 检查手机号码是否有效
      const phoneReg = /^[1][3,4,5,7,8,9][0-9]{9}$/;
      const phones = this.selectedUsers.filter(user => phoneReg.test(user.phone)).map(user => user.phone)
      if(!phones.length) return
      await postSendShortInfo({
        type: "dsp",
        phone: phones,
      })
    },
    // 处理分页
    handlePage(pager) {
      // 需要请求后端
      const { page } = pager;
      this.resForm.page = page
      this.fetchUploadHistory();
    },
    // 请求审批历史记录
    async fetchUploadHistory() {
      this.listLoading = true;
      let dataSource = [];
      let total = 0;
      const queryParam = {
        ...this.resForm,
        owner: this.id,
      }
      if (this.approvalType === "upload") {
        const {
          data: { results, count },
        } = await getUploadApprovalFileHistory(queryParam);
        dataSource = results;
        total = count;
      } else if (this.approvalType === "useCar") {
        const {
          data: { results, count },
        } = await getUseCarApprovalTaskHistory(queryParam);
        dataSource = results;
        total = count;
      } else if (this.approvalType === "officeBuy") {
        const {
          data: { results, count },
        } = await getOfficeBuyApprovalTaskHistory(queryParam);
        dataSource = results;
        total = count;
      } else if (this.approvalType === "holiday") {
        const {
          data: { results, count },
        } = await getHolidayApprovalTaskHistory(queryParam);
        dataSource = results;
        total = count;
      }
      this.tableList = dataSource;
      this.total = total;
      this.listLoading = false;
    },
    // 返回修改人员
    getSelectUsers(users) {
      if (!users.length) return;
      this.selectedUsers = users;
      this.dialogUserVisible = false;
    },
    handleChange(file, fileList) {
      this.fileList = fileList;
    },
    handleRemove(file, fileList) {
      this.fileList = fileList;
    }
  },
};
</script>
<style lang="scss">
.report-material {
  .history,
  .upload-wrapper {
    padding: 12px;
    background: white;
  }
  .el-form-item__label {
    margin-top: 6px;
  }
  .el-upload {
    width: 100%;
    .el-upload-dragger {
      width: 100%;
      height: 220px;
      background: #fafafa;
      .el-icon-upload {
        margin-top: 64px;
      }
    }
  }
}
</style>